package admin

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"mall-go/common"
	"mall-go/dto"
	"mall-go/model"
	"mall-go/repository"
	"mall-go/response"
	"mall-go/util"
	"strconv"
)

type IndexController struct {
	db *gorm.DB
}

// List 获取首页分页数据
func (receiver IndexController) List(ctx *gin.Context) {
	//获取分页数据
	pageNumber, _ := strconv.Atoi(ctx.Query("pageNumber"))
	pageSize, _ := strconv.Atoi(ctx.Query("pageSize"))
	configType, _ := strconv.Atoi(ctx.Query("configType"))
	if pageNumber < 1 || pageSize < 10 {
		panic("参数异常")
	}
	//这里除了1-5其它都是非法参数
	typeNum, _ := util.GetIndexType(configType)
	if typeNum == 0 {
		panic("非法参数")
	}
	//封装DTO
	pageDTO := dto.IndexPageDTO{
		PageDTO: dto.PageDTO{
			Page:  pageNumber,
			Limit: pageSize,
			Start: (pageNumber - 1) * pageSize,
		},
		ConfigType: configType,
	}
	indexConfigRepo := repository.NewIndexConfigRepo()
	pageVO := indexConfigRepo.GetConfigsPage(pageDTO)
	response.Success(ctx, gin.H{"indexVO": pageVO}, "Success")
}

// Save 添加
func (receiver IndexController) Save(ctx *gin.Context) {
	//取出管理员id
	user, _ := ctx.Get("adminUser")
	adminUserId := user.(model.NewBeeAdminUser).AdminUserId
	var param dto.IndexConfigAddParam
	if err := ctx.ShouldBind(&param); err != nil {
		panic(err)
	}
	indexRepo := repository.NewIndexConfigRepo()
	flag := indexRepo.SaveIndexConfig(param, adminUserId)
	if flag {
		response.Success(ctx, nil, "Success")
	}
}

// Edit 修改
func (receiver IndexController) Edit(ctx *gin.Context) {
	//取出管理员id
	user, _ := ctx.Get("adminUser")
	adminUserId := user.(model.NewBeeAdminUser).AdminUserId
	var param dto.IndexConfigEditParam
	if err := ctx.ShouldBind(&param); err != nil {
		panic(err)
	}
	indexRepo := repository.NewIndexConfigRepo()
	flag := indexRepo.UpdateIndexConfig(param, adminUserId)
	if flag {
		response.Success(ctx, nil, "修改成功")
	}
}

// Info 详情
func (receiver IndexController) Info(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Params.ByName("id"))
	var indexConfig model.IndexConfig
	receiver.db.First(&indexConfig, id)
	if indexConfig.ConfigId == 0 {
		panic("查询不到数据")
	}
	response.Success(ctx, gin.H{"indexConfig": indexConfig}, "Success")
}

// BatchDelete 批量删除
func (receiver IndexController) BatchDelete(ctx *gin.Context) {
	//取出管理员id
	user, _ := ctx.Get("adminUser")
	adminUserId := user.(model.NewBeeAdminUser).AdminUserId
	var param dto.BatchIdParam
	ctx.Bind(&param)
	if len(param.UserIds) < 1 {
		panic("参数异常")
	}
	configRepo := repository.NewIndexConfigRepo()
	flag := configRepo.DeleteBatch(param, adminUserId)
	if flag {
		response.Success(ctx, nil, "Success")
	}
}

func NewIndexController() IndexController {
	db := common.GetDB()
	return IndexController{db: db}
}
